package concurrent.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * \* User: Administrator
 * <p>
 * \* Date: 2020/11/26
 * <p>
 * \* Time: 10:57
 * <p>
 * \* Description:
 * \ 模拟情景：5个人开5辆车约定去旅游。到达指定地点一起出发，等待大家都到景区，然后再一起出发
 */
public class CyclicBarrierDemo {
    private static CyclicBarrier barrier = new CyclicBarrier(5, () -> System.out.println("可以出发了"));

    private static void test() {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + "到达-出发-集结点");
                    Thread.sleep(20);
                    barrier.await();

                    System.out.println(Thread.currentThread().getName() + "到达-目的地-集结点");
                    barrier.await(1000, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException | TimeoutException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        test();
//        for (Thread t : list) {
//            t.join();
//        }
        System.out.println("主线程执行完毕");
    }
}
